import { AfterViewInit, Component, EventEmitter, OnDestroy, OnInit, Output, Renderer2, ViewChild } from '@angular/core';
import { ConfigModule } from 'src/app/config.module';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NavigationEnd, Router } from '@angular/router';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { Subject, Subscription } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
import { RoleModel } from '../../../../../models/system/role.model';
import { ValidatorService } from '../../../../../common/validator.service';
import { DragDrop } from '@angular/cdk/drag-drop';
import { UserService } from '../../service/user.service';
import { NzTreeNodeOptions } from 'ng-zorro-antd/core/tree/nz-tree-base-node';

@Component({
    selector: 'app-user-option',
    templateUrl: './index.html',
    styleUrls: ['./index.scss'],
})
export class UserOptionComponent implements OnInit, AfterViewInit, OnDestroy {
    @ViewChild('modalContent') modalContent: any;
    @ViewChild('modalFooter') modalFooter: any;
    @Output() getMainList: EventEmitter<any> = new EventEmitter<any>();
    modalLoadingState: boolean;
    saveLoadingState: boolean;
    roles: Array<RoleModel>;
    dataForm: FormGroup;
    router$: Subscription;
    onDestroy$: Subject<any> = new Subject<any>();
    entity: any = {} as any;
    modalRef: NzModalRef; //用户操作弹窗
    deptTree: Array<any> = [];
    postList: Array<any> = [];
    roleList: Array<any> = [];
    passwordState: any = false;
    constructor(
        public _config: ConfigModule,
        private _formBuilder: FormBuilder,
        private _router: Router,
        private _nzModalService: NzModalService,
        private _validService: ValidatorService,
        private _renderer2: Renderer2,
        private _dragDrop: DragDrop,
        private mainService: UserService,
    ) {
        // 表单验证
        this.dataForm = this._formBuilder.group({
            nickName: ['', [Validators.required]],
            phonenumber: [''],
            userName: ['', [Validators.required]],
            phone: [''],
            email: [''],
            password: [''],
            status: [''],
            roleIds: [''],
            postIds: [''],
            remark: [''],
        });

        this.router$ = this._router.events
            .pipe(
                filter((ev) => ev instanceof NavigationEnd),
                takeUntil(this.onDestroy$)
            )
            .subscribe(() => {
                this.getMainList.emit();
            });
    }

    ngOnInit() {
    }

    ngAfterViewInit() {}

    ngOnDestroy() {
        this.onDestroy$.complete();
    }

    /**
     * 获取部门树形结构
     */
    getDeptTree() {
        this.mainService.deptTree().subscribe(res=>{
            if (res.code === 200){
                this.deptTree = this.convertTreeToList(res.data);
            }
        })
    }

    convertTreeToList(data:any[]): Array<NzTreeNodeOptions> {
        if (!data) return;
        let treeData: NzTreeNodeOptions[] = [];
        data.forEach(node => {
            let treeNode: NzTreeNodeOptions={} as NzTreeNodeOptions;
            treeNode.title = node.label;
            treeNode.expanded = true;
            treeNode.key = node.id;
            treeNode.children = this.convertTreeToList(node.children);
            if (!treeNode.children){
                treeNode.isLeaf = true;
            }
            treeData.push(treeNode);
        })
        return treeData
    }

    /**
     * 操作弹窗
     */
    onModalOpen(id: string) {
        if (id && this.dataForm.contains('userName')){
            this.dataForm.removeControl('userName');
        }else if (!id && !this.dataForm.contains('userName')){
            this.dataForm.addControl('userName', new FormControl(Validators.required));
        }
        this.getDeptTree();
        this.entity.userId = id;
        this.modalRef = this._nzModalService.create({
            nzTitle: id ? '编辑用户' : '新增用户',
            nzContent: this.modalContent,
            nzFooter: this.modalFooter,
            nzWidth: this._config.modalWidth,
            nzBodyStyle: this._config.modalContentHeight,
        });

        this.modalRef.afterOpen.subscribe(() => {
            const modalDragRef = this._renderer2.selectRootElement('.ant-modal-content', true);
            const modalDragHeaderRef = this._renderer2.selectRootElement('.ant-modal-header', true);

            const modalDrag = this._dragDrop.createDrag(modalDragRef);
            modalDrag.withHandles([modalDragHeaderRef]);
            modalDrag.withBoundaryElement(document.body);
        });

        this.modalRef.afterClose.subscribe(() => {
            this.dataForm.reset();
            for (const key of Object.keys(this.entity)) {
                delete this.entity[key];
            }
        });

        if (id) {
            this.modalLoadingState = true;
            this.mainService.get(id).subscribe((res) => {
                if (res.success) {
                    this.entity = res.data;
                    this.entity.postIds = res.postIds;
                    this.entity.roleIds = res.roleIds
                    this.postList = [];
                    res.posts.forEach(item=>{
                        this.postList.push({
                            label: item.postName,
                            value: item.postId
                        })
                    })
                    this.roleList = [];
                    res.roles.forEach(item=>{
                        this.roleList.push({
                            label: item.roleName,
                            value: item.roleId
                        })
                    })
                }
            }).add(() => this.modalLoadingState = false);
        }
    }


    /**
     * 保存
     */
    onSave() {
        if (this.entity.userId) {
            this.mainService.update(this.entity).subscribe((res) => {
                if (res.success) {
                    this.modalRef.close();
                    this.dataForm.reset();
                    for (const key of Object.keys(this.entity)) {
                        delete this.entity[key];
                    }
                    this.getMainList.emit();
                }
            });
        } else {
            this.mainService.add(this.entity).subscribe((res) => {
                if (res.success) {
                    this.modalRef.close();
                    this.dataForm.reset();
                    for (const key of Object.keys(this.entity)) {
                        delete this.entity[key];
                    }
                    this.getMainList.emit();
                }
            });
        }
    }

}
